import { useUserStore } from '@/store/user'
import { useAppStore } from '@/store/app'

// 请求配置接口
interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: Record<string, string>
  timeout?: number
  loading?: boolean
  loadingText?: string
  showError?: boolean
}

// 响应数据接口
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  timestamp: number
}

// 请求拦截器
const requestInterceptor = (config: RequestConfig) => {
  const userStore = useUserStore()
  const appStore = useAppStore()

  // 添加基础URL
  if (!config.url.startsWith('http')) {
    // #ifdef H5
    config.url = '/api' + config.url
    // #endif
    // #ifndef H5
    config.url = 'https://api.accountmanage.com/api' + config.url
    // #endif
  }

  // 添加认证头
  const token = userStore.token || uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    }
  }

  // 添加设备信息
  const deviceInfo = appStore.deviceInfo
  if (deviceInfo) {
    config.header = {
      ...config.header,
      'X-Device-ID': deviceInfo.deviceId,
      'X-Platform': deviceInfo.platform,
      'X-App-Version': deviceInfo.appVersion
    }
  }

  // 添加公共参数
  if (config.method === 'POST' || config.method === 'PUT') {
    config.data = {
      ...config.data,
      device_id: deviceInfo?.deviceId,
      platform: deviceInfo?.platform
    }
  }

  return config
}

// 响应拦截器
const responseInterceptor = (response: any, config: RequestConfig) => {
  const userStore = useUserStore()

  // 检查HTTP状态码
  if (response.statusCode !== 200) {
    throw new Error(`网络错误: ${response.statusCode}`)
  }

  const data: ApiResponse = response.data

  // 检查业务状态码
  if (data.code === 401) {
    // token过期，清除登录状态
    userStore.logout()
    uni.reLaunch({
      url: '/pages/login/index'
    })
    throw new Error('登录已过期，请重新登录')
  }

  if (data.code !== 200) {
    // 显示错误信息
    if (config.showError !== false) {
      uni.showToast({
        title: data.message || '操作失败',
        icon: 'error',
        duration: 2000
      })
    }
    throw new Error(data.message || '操作失败')
  }

  return data.data
}

// 主请求方法
const request = async <T = any>(config: RequestConfig): Promise<T> => {
  // 默认配置
  const defaultConfig: RequestConfig = {
    method: 'GET',
    timeout: 10000,
    loading: false,
    showError: true,
    header: {
      'Content-Type': 'application/json'
    }
  }

  // 合并配置
  const finalConfig = { ...defaultConfig, ...config }

  // 显示加载提示
  if (finalConfig.loading) {
    uni.showLoading({
      title: finalConfig.loadingText || '加载中...',
      mask: true
    })
  }

  try {
    // 请求拦截
    const interceptedConfig = requestInterceptor(finalConfig)

    // 发送请求
    const response = await uni.request({
      url: interceptedConfig.url,
      method: interceptedConfig.method as any,
      data: interceptedConfig.data,
      header: interceptedConfig.header,
      timeout: interceptedConfig.timeout
    })

    // 响应拦截
    const result = responseInterceptor(response, finalConfig)

    return result

  } catch (error: any) {
    // 错误处理
    console.error('请求错误:', error)

    if (finalConfig.showError !== false) {
      const message = error.message || '网络请求失败'
      uni.showToast({
        title: message,
        icon: 'error',
        duration: 2000
      })
    }

    throw error

  } finally {
    // 隐藏加载提示
    if (finalConfig.loading) {
      uni.hideLoading()
    }
  }
}

// 便捷方法
export const http = {
  get: <T = any>(url: string, params?: any, config?: Partial<RequestConfig>) => {
    return request<T>({
      url: params ? `${url}?${buildQuery(params)}` : url,
      method: 'GET',
      ...config
    })
  },

  post: <T = any>(url: string, data?: any, config?: Partial<RequestConfig>) => {
    return request<T>({
      url,
      method: 'POST',
      data,
      ...config
    })
  },

  put: <T = any>(url: string, data?: any, config?: Partial<RequestConfig>) => {
    return request<T>({
      url,
      method: 'PUT',
      data,
      ...config
    })
  },

  delete: <T = any>(url: string, config?: Partial<RequestConfig>) => {
    return request<T>({
      url,
      method: 'DELETE',
      ...config
    })
  }
}

// 构建查询字符串
const buildQuery = (params: Record<string, any>): string => {
  const query = new URLSearchParams()

  Object.keys(params).forEach(key => {
    const value = params[key]
    if (value !== undefined && value !== null && value !== '') {
      query.append(key, String(value))
    }
  })

  return query.toString()
}

export default request